#include "diffdialog.h"
#include "databasediff.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QListWidget>
#include <QPushButton>
#include <QTextEdit>
#include <QDialogButtonBox>
#include <QFileDialog>
#include <QMessageBox>
#include <QProgressDialog>
#include <QSqlDatabase>
#include <QApplication>
#include <QFile>
#include <QTextStream>

DiffDialog::DiffDialog(const QSqlDatabase &db, QWidget *parent)
    : QDialog(parent)
    , m_database(db)
{
    setupUI();
    loadDatabases();
    
    // 初始化数据库比较器
    m_databaseDiff = new DatabaseDiff(this);
    
    // 连接信号和槽
    connect(m_databaseDiff, &DatabaseDiff::comparisonFinished, 
            this, [this](const DatabaseDifference &diff) {
                m_currentDiff = diff;
                m_resultText->setText(diff.summary);
                m_detailsButton->setEnabled(true);
                m_saveButton->setEnabled(true);
            });
            
    connect(m_databaseDiff, &DatabaseDiff::comparisonError,
            this, [this](const QString &error) {
                QMessageBox::warning(this, tr("Comparison Error"), error);
            });
}

void DiffDialog::compareDatabases()
{
    // 获取选中的数据库
    QList<QListWidgetItem *> selected = m_databaseList->selectedItems();
    if (selected.isEmpty()) {
        QMessageBox::information(this, tr("Information"), tr("Please select a database to compare with."));
        return;
    }
    
    QString selectedDbName = selected.first()->text();
    
    // 获取选中的数据库连接
    QSqlDatabase db2 = QSqlDatabase::database(selectedDbName);
    if (!db2.isOpen()) {
        QMessageBox::warning(this, tr("Error"), tr("Selected database is not open."));
        return;
    }
    
    // 创建进度对话框
    QProgressDialog progressDialog(tr("Comparing databases..."), tr("Cancel"), 0, 100, this);
    progressDialog.setWindowModality(Qt::WindowModal);
    progressDialog.setAutoClose(false);
    progressDialog.setAutoReset(false);
    
    connect(m_databaseDiff, &DatabaseDiff::comparisonProgress, 
            &progressDialog, &QProgressDialog::setValue);
    
    // 执行比较
    m_databaseDiff->compareDatabases(m_database, db2);
}

void DiffDialog::showDifferenceDetails()
{
    QString details = m_currentDiff.summary + "\n\n" + tr("Detailed differences:\n");
    
    for (const auto &diff : m_currentDiff.tableDifferences) {
        QString typeStr;
        switch (diff.type) {
        case TableDifference::Added:
            typeStr = tr("Added");
            break;
        case TableDifference::Removed:
            typeStr = tr("Removed");
            break;
        case TableDifference::Modified:
            typeStr = tr("Modified");
            break;
        }
        
        details += QString("- [%1] %2: %3\n").arg(typeStr).arg(diff.tableName).arg(diff.details);
    }
    
    m_resultText->setText(details);
}

void DiffDialog::saveReport()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save Report"), 
                                                   "database_diff_report.txt",
                                                   tr("Text Files (*.txt);;All Files (*)"));
    if (fileName.isEmpty()) {
        return;
    }
    
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(this, tr("Error"), tr("Cannot write to file %1").arg(fileName));
        return;
    }
    
    QTextStream out(&file);
    out << m_resultText->toPlainText();
    file.close();
    
    QMessageBox::information(this, tr("Success"), tr("Report saved to %1").arg(fileName));
}

void DiffDialog::setupUI()
{
    setWindowTitle(tr("Database Comparison"));
    setModal(true);
    resize(600, 400);
    
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    
    // 说明标签
    QLabel *infoLabel = new QLabel(tr("Select a database to compare with the current one:"));
    mainLayout->addWidget(infoLabel);
    
    // 数据库列表
    m_databaseList = new QListWidget;
    mainLayout->addWidget(m_databaseList);
    
    // 按钮布局
    QHBoxLayout *buttonLayout = new QHBoxLayout;
    
    m_compareButton = new QPushButton(tr("Compare"));
    m_detailsButton = new QPushButton(tr("Show Details"));
    m_detailsButton->setEnabled(false);
    m_saveButton = new QPushButton(tr("Save Report"));
    m_saveButton->setEnabled(false);
    
    buttonLayout->addWidget(m_compareButton);
    buttonLayout->addWidget(m_detailsButton);
    buttonLayout->addWidget(m_saveButton);
    buttonLayout->addStretch();
    
    mainLayout->addLayout(buttonLayout);
    
    // 结果显示区域
    m_resultText = new QTextEdit;
    m_resultText->setReadOnly(true);
    mainLayout->addWidget(m_resultText);
    
    // 对话框按钮
    m_buttonBox = new QDialogButtonBox(QDialogButtonBox::Close);
    mainLayout->addWidget(m_buttonBox);
    
    // 连接信号和槽
    connect(m_compareButton, &QPushButton::clicked, this, &DiffDialog::compareDatabases);
    connect(m_detailsButton, &QPushButton::clicked, this, &DiffDialog::showDifferenceDetails);
    connect(m_saveButton, &QPushButton::clicked, this, &DiffDialog::saveReport);
    connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
}

void DiffDialog::loadDatabases()
{
    m_databaseList->clear();
    
    // 获取所有打开的数据库连接
    QStringList connectionNames = QSqlDatabase::connectionNames();
    for (const QString &name : connectionNames) {
        // 排除当前数据库
        if (name != m_database.connectionName()) {
            QSqlDatabase db = QSqlDatabase::database(name);
            if (db.isOpen()) {
                m_databaseList->addItem(name + " (" + db.databaseName() + ")");
            }
        }
    }
}